package team.paimengshop.server_socket;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import team.paimengshop.server_database.*;
import team.paimengshop.server_dataclass.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import team.paimengshop.show.*;

public class ActionControl_Receive
{
    private static customerServiceforServerController customerServiceforServerController;


    public static void setCustomerServiceforServerController(team.paimengshop.show.customerServiceforServerController customerServiceforServerController)
    {
        ActionControl_Receive.customerServiceforServerController = customerServiceforServerController;
    }

    public static team.paimengshop.show.customerServiceforServerController getCustomerServiceforServerController()
    {
        return customerServiceforServerController;
    }


    public ActionControl_Receive()
    {

    }

    public static JSONArray Login(JSONObject jsonObject)
    {
            String email = jsonObject.get("email").toString();
            String password = jsonObject.get("password").toString();
            String feedback = "";
            User user = UserInfoOperate.FindByEmail(email);
            if (user.getId() == -1)
            {
                feedback = "not registered";
            } else
            {
                if (user.getPassword().equals(password))
                {
                    feedback = "login succeed";
                    System.out.println("用户" + user.getId() + "登录");
                } else
                {
                    feedback = "wrong password";
                }
            }
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("login and register", "login");
            jsonObj.put("feedback", feedback);
            jsonObj.put("id", Integer.toString(user.getId()));
            jsonObj.put("email", user.getEmail());
            jsonObj.put("password", user.getPassword());
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObj);
            return jsonArray;

    }

    public static JSONArray Register(JSONObject jsonObject)
    {
        String feedback = "";
        if(jsonObject.containsKey("verCode"))
        {
            if(MailControl.getEmailAndVerCodeJsonObject().containsKey(jsonObject.get("email").toString()))
            {
                if(jsonObject.get("verCode").toString().equals(MailControl.getEmailAndVerCodeJsonObject().get(jsonObject.get("email").toString())))
                {
                    feedback = "register succeed";
                    String email = jsonObject.get("email").toString();
                    String password = jsonObject.get("password").toString();
                    UserInfoOperate.Add(email, email, password, "file:PaiMengShop/PaiMengShopClient/src/main/resources/com/example/paimengshop/faceImage/normalFaceImage.jpg", "", "", "提瓦特大陆");
                }
                else
                {
                    feedback = "wrong verCode";
                }

            }
            else
            {
                System.out.println("getEmailAndVerCodeJsonObject出错！");
            }
        }
        else
        {
            String email = jsonObject.get("email").toString();
            String password = jsonObject.get("password").toString();
            User user = UserInfoOperate.FindByEmail(email);
            if (user.getId() == -1)
            {
                int verCode = MailControl.CreateVerCode();
                MailControl.SendEmail(email, verCode);
                MailControl.getEmailAndVerCodeJsonObject().put(email, Integer.toString(verCode));
                feedback = "please input verCode";
            } else
            {
                feedback = "already registered";
            }
        }
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("login and register", "register");
        jsonObj.put("feedback", feedback);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObj);
        return jsonArray;
    }

    public static void ChangeUserName(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String userName = jsonObject.get("userName").toString();
        if(UserInfoOperate.UpdateUserName(id, userName) == 1)
        {
            System.out.println("用户" + id + "修改了userName");
        }
    }

    public static void ChangeAddress(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String address = jsonObject.get("address").toString();
        if(UserInfoOperate.UpdateAddress(id, address) == 1)
        {
            System.out.println("用户" + id + "修改了address");
        }
    }

    public static void ChangeHeadImageURL(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String headImageURL = jsonObject.get("headImageURL").toString();
        if(UserInfoOperate.UpdateHeadImageURL(id, headImageURL) == 1)
        {
            System.out.println("用户" + id + "修改了headImageURL");
        }
    }

    public static JSONArray ChangePassword(JSONObject jsonObject)
    {
        String feedback = "";
        if(jsonObject.containsKey("verCode"))
        {
            if(MailControl.getEmailAndVerCodeJsonObject().containsKey(jsonObject.get("email").toString()))
            {
                if(jsonObject.get("verCode").toString().equals(MailControl.getEmailAndVerCodeJsonObject().get(jsonObject.get("email").toString())))
                {
                    feedback = "change succeed";
                    String email = jsonObject.get("email").toString();
                    String newPassword = jsonObject.get("new password").toString();
                    if(UserInfoOperate.UpdatePassword(email, newPassword) == 1)
                    {
                        int id = UserInfoOperate.GetIdByEmail(email);
                        System.out.println("用户" + id + "修改了password");
                    }
                }
                else
                {
                    feedback = "wrong verCode";
                }
                //MailControl.getEmailAndVerCodeJsonObject().remove(jsonObject.get("email").toString());
            }
            else
            {
                System.out.println("getEmailAndVerCodeJsonObject出错！");
            }
        }
        else
        {
            String email = jsonObject.get("email").toString();
            String password = jsonObject.get("password").toString();
            User user = UserInfoOperate.FindByEmail(email);
            if (user.getId() != -1)
            {
                int verCode = MailControl.CreateVerCode();
                MailControl.SendEmail(email, verCode);
                MailControl.getEmailAndVerCodeJsonObject().put(email, Integer.toString(verCode));
                feedback = "please input verCode";
            } else
            {
                feedback = "not registered";
            }
        }
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("change password", "");
        jsonObj.put("feedback", feedback);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObj);
        return jsonArray;
    }

    public static void UpdateCart(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String commodityList = jsonObject.get("commodityArrayList").toString();
        if(UserInfoOperate.UpdateCart(id, commodityList) == 1)
        {
            System.out.println("用户" + id + "更新了购物车");
        }
    }

    public static void UpdateCollection(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String commodityList = jsonObject.get("commodityArrayList").toString();
        if(UserInfoOperate.UpdateCollection(id, commodityList) == 1)
        {
            System.out.println("用户" + id + "更新了收藏");
        }
    }

    public static void CreateOrder(JSONObject jsonObject)
    {
        int id = Integer.parseInt(jsonObject.get("userId").toString());
        String address = jsonObject.get("address").toString();
        String commodityList = jsonObject.get("commodityArrayList").toString();
        int commodityNumber = Integer.parseInt(jsonObject.get("commodity number").toString());
        double payment = Double.parseDouble(jsonObject.get("payment").toString());
        OrderOperate.Add(id, address, commodityList, commodityNumber, payment);
    }

    public static String Communication_Message(JSONObject jsonObject)
    {
        return jsonObject.get("message").toString();
    }

    public static File Communication_Image(JSONObject jsonObject)
    {
        byte[] src = (byte[]) jsonObject.get("image");
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String imageName = jsonObject.get("userId").toString();
        imageName += "_" + dateFormat.format(date) + ".jpg";
        String path = "PaiMengShop/PaiMengShopServer/src/main/resources/team/paimengshop/show/chatImage/" + imageName;
        File dest = new File(path);

        // 2、选择流
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new ByteArrayInputStream(src);
            os = new FileOutputStream(dest);
            // 3、操作(分段读取)
            byte[] flush = new byte[5];// 缓冲容器
            int len = -1;// 接收长度
            while ((len = is.read(flush)) != -1) {
                os.write(flush,0,len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dest;
    }
}
